<template>
	<el-row :gutter="20">
	    <el-col :span="12" :offset="6">
	      <el-form
	          ref="ruleFormRef"
	          style="max-width: 600px"
	          :model="ruleForm"
	          status-icon
	          :rules="rules"
	          label-width="auto"
	          class="demo-ruleForm"
	        >
			  <el-form-item label="用户名" prop="username">
				<el-input v-model="ruleForm.username" type="text" autocomplete="off" />
			  </el-form-item>
	          <el-form-item label="密码" prop="password">
	            <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
	          </el-form-item>
	          <el-form-item>
	            <el-button type="primary" @click="submitForm">登录</el-button>
	            <el-button @click="resetForm">重置</el-button>
	          </el-form-item>
	        </el-form>
	    </el-col>
	  </el-row>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { reactive, ref , getCurrentInstance} from 'vue'

	//获取当前实例   方便发送axios请求
    let {proxy} = getCurrentInstance();

    //通过ref属性值来获取Form元素
	const ruleFormRef = ref(null);

	const ruleForm = reactive({
	  username: '',
	  password: ''
	})

    //表单校验规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
		{ min: 4, message: '用户名不能小于4位', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
      ]
    }
	
	//点击登录调用
	const submitForm = () => {
		  //校验表单
	      ruleFormRef.value.validate((valid) => {
	        if (valid) {
				console.log('发送登录请求!')
				//校验成功  发送登录请求
				  proxy.$axios({
					  method: 'post',
					  url: '/log/in',
					  data: ruleForm
				  }).then(res=>{
					  let resultBean = res.data;
					  if(resultBean.code == 200){
						  //将登录成功的用户名存入本地存储
						  window.localStorage.setItem("adminUser",resultBean.data);
						  //路由跳转到主页面
						  proxy.$router.push("/main");
					  }else{
						  ElMessage.error(resultBean.msg);
					  }
				  })
	        } else {
				ElMessage.error('提交失败');
	          return false
	        }
	      })
	    }
	
	    //表单重置
	    const resetForm = () => {
	      ruleFormRef.value.resetFields()
	    }



</script>

<style scoped>
	.el-row {
	  margin-top: 200px;
	}
</style>